/*
 * Created by zhumin on 2021/3/8.
 */
import Vue from 'vue'
import Storage from '@/assets/js/storage.js'
import CryptoJS from 'crypto-js/crypto-js'
import moment from 'moment'

const Base64 = require('js-base64').Base64
const KEY = CryptoJS.enc.Utf8.parse('1234567890123456')
const IV = CryptoJS.enc.Utf8.parse('1234567890123456')

//加密
function Encrypt(word, keyStr, ivStr) {
  let key = KEY
  let iv = IV

  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr)
    iv = CryptoJS.enc.Utf8.parse(ivStr)
  }

  let srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  })
  // console.log("-=-=-=-", encrypted.ciphertext)
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}

//获取今日时间
function showToDay(val) {
  var date = new Date()
  let M = (date.getMonth() < 9 ? '0' : '') + (Number(date.getMonth()) + 1)
  let D = (date.getDate() < 10 ? '0' : '') + date.getDate()
  let time = ''
  if (val === 'start') time = ' 00:00:00'
  else {
    var hour = date.getHours() //得到小时
    var minu = date.getMinutes() //得到分钟
    var sec = date.getSeconds() //得到秒
    if (hour < 10) hour = '0' + hour
    if (minu < 10) minu = '0' + minu
    if (sec < 10) sec = '0' + sec
    time = ' ' + hour + ':' + minu + ':' + sec
  }
  return date.getFullYear() + '-' + M + '-' + D + time
}

//获取本周第一天
function showWeekFirstDay() {
  var date = new Date()
  var WeekFirstDay = new Date(date - (date.getDay() - 1) * 86400000)
  let M = (WeekFirstDay.getMonth() < 9 ? '0' : '') + (Number(WeekFirstDay.getMonth()) + 1)
  let D = (WeekFirstDay.getDate() < 10 ? '0' : '') + WeekFirstDay.getDate()
  return WeekFirstDay.getFullYear() + '-' + M + '-' + D + ' 00:00:00'
}

//获取本周最后一天
function showWeekLastDay() {
  var date = new Date()
  var WeekFirstDay = new Date(date - (date.getDay() - 1) * 86400000)
  var WeekLastDay = new Date((WeekFirstDay / 1000 + 6 * 86400) * 1000)
  let M = (WeekLastDay.getMonth() < 9 ? '0' : '') + (Number(WeekLastDay.getMonth()) + 1)
  let D = (WeekLastDay.getDate() < 10 ? '0' : '') + WeekLastDay.getDate()
  return WeekLastDay.getFullYear() + '-' + M + '-' + D + ' 23:59:59'
}

//获取本月第一天
function showMonthFirstDay() {
  var date = new Date()
  var MonthFirstDay = new Date(date.getFullYear(), date.getMonth(), 1)
  let M = (MonthFirstDay.getMonth() < 9 ? '0' : '') + (Number(MonthFirstDay.getMonth()) + 1)
  let D = (MonthFirstDay.getDate() < 10 ? '0' : '') + MonthFirstDay.getDate()
  return MonthFirstDay.getFullYear() + '-' + M + '-' + D + ' 00:00:00'
}

//获取本月最后一天
function showMonthLastDay() {
  var date = new Date()
  var MonthNextFirstDay = new Date(date.getFullYear(), date.getMonth() + 1, 1)
  var MonthLastDay = new Date(MonthNextFirstDay - 86400000)
  let M = (MonthLastDay.getMonth() < 9 ? '0' : '') + (Number(MonthLastDay.getMonth()) + 1)
  let D = (MonthLastDay.getDate() < 10 ? '0' : '') + MonthLastDay.getDate()
  return MonthLastDay.getFullYear() + '-' + M + '-' + D + ' 23:59:59'
}

function isEmpty(val) {
  if (val === null || val === undefined || val === '') {
    return true
  }
  return false
}

function jsonToString(data) {
  let str = []
  for (let p in data) {
    if (Object.prototype.hasOwnProperty.call(data, p)) {
      str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p]))
    }
  }
  return str.join('&')
}

function baseAuth() {
  let token = 'Basic ' + Base64.encode('csmc-client-browser:csmc-client-browser-secret')
  return token
}

//特殊字符（密码）
function checkSpecificKey(str) {
  var specialKey = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'"
  for (var i = 0; i < str.length; i++) {
    if (specialKey.indexOf(str.substr(i, 1)) != -1) {
      return false
    }
  }
  return true
}

//测试环境映射关系
const TEST_POOL = {
  'CIDC-RP-25': '/ice/'
}
const TESTDEV_POOL = {
  'CIDC-RP-25': '/ice/'
}
//现网环境映射关系
const POOL = {
  'CIDC-RP-25': '/ice/'
}

//获取当前资源池信息
const poolId = Storage.get('poolId', 'CIDC-RP-25')
let API_PATH = ''
const ENV_TYPE = process.env.VUE_APP_ENV_TYPE
if (ENV_TYPE === 'development') {
  API_PATH = process.env.VUE_APP_API_PATH
} else if (ENV_TYPE === 'test') {
  API_PATH = TEST_POOL[poolId]
} else if (ENV_TYPE === 'testDev') {
  //API_PATH = process.env.VUE_APP_API_PATH
  API_PATH = TESTDEV_POOL[poolId]
} else if (ENV_TYPE === 'production') {
  API_PATH = POOL[poolId]
}

export default {
  isEmpty,
  jsonToString,
  API_PATH,
  poolId,
  Encrypt,
  showToDay,
  showWeekFirstDay,
  showWeekLastDay,
  showMonthFirstDay,
  showMonthLastDay,
  /*
   *
   *
   * 以下为封装的axios方法
   */
  axiosGet(url, commit, clearMutation, requestMutation) {
    return Vue.axios
      .get(url)
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  //post
  axiosPost(url, data = {}) {
    url = API_PATH + url
    return new Promise((resolve, reject) => {
      Vue.axios.post(url, data).then(
        response => {
          resolve(response.data)
        },
        err => {
          reject(err)
        }
      )
    })
  },
  axiosPostJson(url, data = {}) {
    url = API_PATH + url
    return new Promise((resolve, reject) => {
      Vue.axios
        .post(url, data, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        .then(
          response => {
            resolve(response.data)
          },
          err => {
            reject(err)
          }
        )
    })
  },
  //PUT
  axiosPut(url, data = {}) {
    url = API_PATH + url
    return new Promise((resolve, reject) => {
      Vue.axios.put(url, data).then(
        response => {
          resolve(response.data)
        },
        err => {
          reject(err)
        }
      )
    })
  },
  //DELETE
  axiosDelete(url, data = {}) {
    url = API_PATH + url
    return new Promise((resolve, reject) => {
      Vue.axios.delete(url, data).then(
        response => {
          resolve(response.data)
        },
        err => {
          reject(err)
        }
      )
    })
  },
  //与VUEX相结合的方法
  postAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url
    return Vue.axios
      .post(url, params)
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  //登录basic auth
  postAuthAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url
    return Vue.axios
      .post(url, params, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: baseAuth(),
          version: 'V1.0',
          type: process.env.VUE_APP_ENV_TYPE
        }
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.data.code === '000000000000') {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  message: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  postJSONAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url
    return Vue.axios
      .post(url, params, {
        headers: {
          'Content-Type': 'application/json',
          version: 'V1.0'
        }
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  postDWLDAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url
    return Vue.axios
      .post(url, params, {
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: 'blob'
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (requestMutation !== '') {
          commit(requestMutation, response.data)
        }
        return Promise.resolve(response.data)
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  getAction(url, commit, clearMutation, requestMutation) {
    url = API_PATH + url
    return Vue.axios
      .get(url)
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  getDWLDAction(url, commit, clearMutation, requestMutation) {
    url = API_PATH + url
    return Vue.axios
      .get(url, {
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: 'blob'
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (requestMutation !== '') {
          commit(requestMutation, response.data)
        }
        return Promise.resolve(response.data)
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  putAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url
    return Vue.axios
      .put(url, params)
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  putJSONAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url
    return Vue.axios
      .put(url, params, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  deleteAction(url, commit, clearMutation, requestMutation) {
    url = API_PATH + url
    return Vue.axios
      .delete(url)
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  deleteJSONAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url
    return Vue.axios
      .delete(url, {
        data: params,
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.data.code === '000000000000') {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  message: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  //复制功能
  copy(msg) {
    let input = document.createElement('input')
    input.value = msg
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
    Vue.prototype.$message.success('复制成功!')
  },
  //时间戳转换
  timeFormat(time) {
    if (time) {
      return moment(time)
        .add(8, 'hours')
        .format('YYYY-MM-DD HH:mm:ss')
    }
  },
  formatDate(value) {
    return moment(value).format('YYYY-MM-DD HH:mm:ss')
  },
  formatTime(value) {
    if (value === 'start') {
      return moment()
        .subtract(1, 'days')
        .format('YYYY-MM-DD 00:00:00')
    }
    return moment().format('YYYY-MM-DD HH:mm:ss')
  },
  debounce(fn, delay) {
    let timer = null
    return function() {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        fn()
      }, delay)
    }
  }
}
